<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/4
 * Time: 15:55
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;

use Illuminate\Support\Facades\Request;
use DB;
use \Illuminate\Support\Facades\Input;
use App\ModelStatistic\StatisticCommon;
class AreaOrder extends Model{
    // 订单状态
    public static $order_status = [0=> 'success', 1=> 'success', 2 => 'fail', 5 => 'test'];
    public static function paginate()
    {
        $cp_area = Request::get('cp_area');
        $perPage = Request::get('per_page', 20);
        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

        $tableAccount = 'platsdk_order';
        $rw = \DB::connection('mysql_bgac')->table($tableAccount);
        self::SourceCondition($rw, $cp_area);
        $rw->orderBy('id', "DESC");
        $total = $rw->get()->count();
        $rw = $rw->skip($start)->take($perPage);
        $data = $rw->get();
        $data = $data->toArray();
//        var_dump($data);exit();

        // $data = json_decode($data, true);
        // \Log::debug(__METHOD__, [self::GetRechargeAlias()]);
        // 加入多语言字段
        $alias_trans_list = \App\Models\Pay\Recharge::GetRechargeAlias();

        $recharge_price = \App\Models\Pay\Recharge::getAll();
        $account_list = $account_ids = [];
        foreach ($data as &$obj) {
            $obj->prop_name = $alias_trans_list[$obj->cp_product_id ];

            $conf_one = $recharge_price[$obj->cp_product_id ]?:[];
            $obj->game_rmb = $conf_one['rmb'];
            $obj->game_lyto = $conf_one['dollar'];

            $obj->cp_rmb = round($obj->cp_rmb / 100, 2);
            $account_ids[] = $obj->cp_account;
        }
        
        // 附加account 信息
        $account_list = \App\Models\Account\PlayerActModel::getAccountList($account_ids);
        
        foreach($data as &$obj) {
            $acc = $account_list[$obj->cp_account]?:[];
            $obj->device            = $acc['udid'];
            $obj->account_time      = $acc['createTime'];
        }

        // \Log::debug('[AreaOrder][LIST]', [$account_ids,$account_list]);
        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());
//var_dump($paginator);exit();
        return $paginator;
    }

    //模糊查询
    public static function SourceCondition(&$rw, $area)
    {
        $cond = Request::all();
        $area_extend = \App\Models\Area::GetAreaExtendInfo($area);

        if ($cond['OrderSerial']){
            $rw->where("OrderSerial", 'like', $cond["OrderSerial"].'%');
        }
        if ($cond['CooperatorOrderSerial']){
            $rw->where("CooperatorOrderSerial", 'like', $cond["CooperatorOrderSerial"].'%');
        }

        if ($cond['cp_player_id']){
            $rw->where("cp_player_id", '=', $cond["cp_player_id"]);
        }
        if ($cond['cp_account']){
            $rw->where("cp_account", '=', $cond["cp_account"]);
        }

        if ($cond['cp_product_id']){
            $rw->where("cp_product_id", '=', $cond["cp_product_id"]);
        }

        $cond["charge_ok"] = Input::get('charge_ok', 1);
        if ($cond["charge_ok"]){
            $rw->where("OrderSerial", "<>", "");
        }

        $created_time = Request::get('created_time', []);
        // 默认仅仅查第一天的数据
        $start_time = StatisticCommon::GetIntTime($created_time['start'] ? : strtotime(date('Y-m-d',time())) );
        if ($start_time) {
            $rw->where('created_time', ">=",  $start_time);
        }

        $end_time = StatisticCommon::GetIntTime($created_time['end']);
        if ($end_time) {
            $rw->where('created_time', "<=", $end_time );
        }

        if ($cond['cp_area']) {
            $rw->where('cp_area','=',$cond['cp_area']);
        }

        $status_arr = [];
        if (!$cond['OrderStatus'] || $cond['OrderStatus'] == 1) {
            $status_arr = [0, 1];
        }else {
            $status_arr = [$cond['OrderStatus'] ];
        }

        $rw->whereIn('OrderStatus', $status_arr);
        
        $deleted_no = $cond['deleted_at'] ?: 0;
        $rw->where('deleted_at','=', $deleted_no);
        \Log::debug('order list area created_time', [$rw->toSql(), $start_time, $end_time]);
    }


    // 实现自定义导出数据源
    public static function getCustomExportData()
    {
        $cp_area = Request::get('cp_area');
        $tableAccount = 'platsdk_order';
        $rw = \DB::connection('mysql_bgac')->table($tableAccount);
        self::SourceCondition($rw, $cp_area);
        $rw->orderBy('id', "DESC");
        $data = $rw->get()->toArray();

        $alias_trans_list = \App\Models\Pay\Recharge::GetRechargeAlias();
        $recharge_json = \App\Models\Pay\Recharge::getAll();
        
        $export_data = [];
        foreach ($data as $obj) {
            $tmp_arr = [];
            foreach(self::getCustomExportHead() as $attr => $value){
                $tmp_arr[$attr] = $obj->{$attr} ?:' ';
            }

            // 覆盖值
            $conf_one = $recharge_json[$obj->cp_product_id ]?:[];
            $tmp_arr['game_rmb'] = $conf_one['rmb'];
            
            $tmp_arr['prop_name'] = $alias_trans_list[$obj->cp_product_id ];

            $export_data[] = $tmp_arr;
        }
        \Log::debug(__METHOD__, ['custom define success!', 'export count'=> $rw->count()]);
        return $export_data;
    }

    public static function find($CooperatorOrderSerial){
        $tableAccount = 'platsdk_order';
        $data = \DB::connection('mysql_bgac')->table($tableAccount)->where('CooperatorOrderSerial','=',$CooperatorOrderSerial)->first();
        return $data;
    }

    public static function RepairOrder($one, $OrderSerial) {
        if (!$one->CooperatorOrderSerial || !$OrderSerial)
        {
            return false;
        }
        
        // 修复订单
        $ret = \DB::connection('mysql_bgac')->table('platsdk_order')->where('CooperatorOrderSerial','=',$one->CooperatorOrderSerial)->update(['OrderSerial' => $OrderSerial]);

        // 插入补充订单的记录
        \DB::connection('mysql_bgac')->table('platsdk_order_repair')->insert([
            'plat_order_id' => $OrderSerial,
            'cp_area'       => $one->cp_area,
            'created_time'  => time(),
        ]);
        return $ret;
    }

    // 软删除订单
    public static function deleteSoft($CooperatorOrderSerial){
        $ret = \DB::connection('mysql_bgac')->table('platsdk_order')->where('CooperatorOrderSerial','=',$CooperatorOrderSerial)->update(['deleted_at' => 1]);
    }

    // 发送补单消息给game
    public static function sendRepairMsg($one, $data = null){
        $data['accesstoken'] = null;
        $data['timestamp'] = time();
        $data['msgid'] = 0xF001;
        $data['cp_area'] = \App\Models\Area::getPhysicsArea($one->cp_area);
        $data['ExtInfo'] = json_decode($one->cp_extra, true);
        $data['OrderSerial'] = $one->OrderSerial;
        $data['CooperatorOrderSerial'] = $one->CooperatorOrderSerial;
        \Log::debug(__METHOD__, $data);
        \App\Models\SendSocketToGame::SendAction(function($socket)use($one, $data){

            $ret = $socket->send($data);
            // \Log::debug('send single player mail'. json_encode($data) );

            $read_data = $socket->ReadHttpReponse();
            \Log::debug('Send Order Repair data', [$read_data]);
        });
    }

    public static function getCustomExportHead()
    {
        return [
            'id'            =>  'ID',
            'OrderSerial'   =>  'OrderSerial',
            'cp_account'    =>  'Account',
            'cp_player_id'  =>  'Player ID',
            'cp_product_id' =>  'CP Proo ID',
            'prop_name'     =>  'Prop Name',
            'game_rmb'      =>  'Game RMB',
            'updated_at'    =>  'Date Time',
        ];
    }
}